# frozen_string_literal: true

module Issues
  class CreateFromVulnerabilityService < ::BaseService
    def execute
      return error("User is not permitted to create issue") unless can?(@current_user, :create_issue, @project)

      vulnerability = params.fetch(:vulnerability)

      issue_params = {
        title: title_for(vulnerability),
        description: render_description(vulnerability),
        confidential: true
      }

      # NOTE: Intentionally not performing spam check, for now.
      result = Issues::CreateService
        .new(container: @project, current_user: @current_user, params: issue_params, perform_spam_check: false)
        .execute

      if result.success?
        success(result[:issue])
      else
        error(result.errors.join(', '))
      end
    end

    private

    def title_for(vulnerability)
      "Investigate vulnerability: #{vulnerability.title}".truncate(::Issuable::TITLE_LENGTH_MAX)
    end

    def success(issue)
      super().merge(issue: issue)
    end

    def render_description(vulnerability)
      ApplicationController.render(
        template: 'vulnerabilities/issue_description',
        formats: :md,
        locals: { vulnerability: vulnerability.present }
      )
    end
  end
end
